package com.karl.mytask_2.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.karl.mytask_2.R;
import com.karl.mytask_2.bean.MyUser;
import com.karl.mytask_2.tools.BaseActivity;


import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.UpdateListener;

/**
 * Created by Karl on 2016/5/27.
 */
public class Info_NickName extends BaseActivity implements View.OnClickListener {
    private TextView mToolBarTitle;
    private ImageButton mBack;

    private Button mSave;
    private EditText mEdt;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.info_nickname);
        initView();

    }
    private void initView(){
        mToolBarTitle = (TextView) findViewById(R.id.tool_bar2_title);
        mBack = (ImageButton) findViewById(R.id.tool_bar2_back);

        mSave = (Button) findViewById(R.id.nick_name_btn);
        mEdt = (EditText) findViewById(R.id.nick_name_edt);

        initEvent();
    }
    private void initEvent(){
        mToolBarTitle.setText("更新用户名");
        mBack.setOnClickListener(this);
        mSave.setOnClickListener(this);

        Intent intent = getIntent();
        String name = intent.getStringExtra("name");
        mEdt.setText(name);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.nick_name_btn:
                saveName();
                break;
            case R.id.tool_bar2_back:
                Info_NickName.this.finish();
                break;
        }
    }
    private void saveName(){
        String name = mEdt.getText().toString();
        updateName(name);
    }

    private void updateName(final String name){
        MyUser user = BmobUser.getCurrentUser(this,MyUser.class);
        MyUser nUser = new MyUser();
        nUser.setNickName(name);
        nUser.update(this, user.getObjectId(), new UpdateListener() {
            @Override
            public void onSuccess() {
                Toast.makeText(Info_NickName.this, "保存成功！", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent();
                setResult(RESULT_OK, intent);
                Info_NickName.this.finish();

            }

            @Override
            public void onFailure(int i, String s) {
                Toast.makeText(Info_NickName.this, "保存失败，请检查网络", Toast.LENGTH_SHORT).show();
            }
        });

    }
}
